<template>
  <div style="width: 100%; height: 100%">
    <el-container
      ref="listWarp"
      style="height: 100%; background-color: #fff"
      v-loading="loading"
    >
      <div
        class="win-warp"
        style="
          height: auto;
          width: 1200px;
          background-color: #fff;
          margin: 0 auto;
          margin-top: 30px;
        "
      >
        <div
          style="
            width: 100%;
            text-align: center;
            font-size: 20px;
            padding-bottom: 35px;
          "
        >
          办公用房申请表
        </div>
        <el-row :gutter="12">
          <el-form
            ref="elForm"
            :model="formData"
            :rules="rules"
            size="small"
            label-width="120px"
          >
            <el-col :span="12">
              <el-form-item label="申请房屋类型" prop="houseTypeId">
                <el-select
                  size="small"
                  @change="evtHouseType"
                  style="width: 100%"
                  v-model="formData.houseTypeId"
                  placeholder="请选择房屋类型"
                  filterable
                >
                  <el-option
                    v-for="(item, index) in houseTypeList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请类型" prop="flowType">
                <el-select
                  v-model="formData.flowType"
                  placeholder="请选择申请类型"
                  filterable
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in applyType"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
              <el-col :span="12" v-if="formData.flowType == '2' || formData.flowType == '3'">
                <el-form-item label="退宿房间" prop="oldRoomInId">
                  <el-select
                    v-model="formData.oldRoomInId"
                    placeholder="请选择退宿房间"
                    filterable
                    clearable
                    :style="{ width: '100%' }"
                    @change="ifLive"
                  >
                    <el-option
                      v-for="(item, index) in oldRoomList"
                      :key="index"
                      :label="item.roomNum"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="userName">
                <!-- <el-input
                  v-model="formData.userName"
                  placeholder="请输入姓名"
                  clearable
                  :style="{ width: '100%' }"
                ></el-input> -->
                <el-select
                  v-model="formData.userName"
                  placeholder="请选择使用人"
                  filterable
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in userList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所在部门" prop="userDeptName">
                <el-input
                  v-model="formData.userDeptName"
                  disabled
                  placeholder="请选择部门"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-button
                    slot="append"
                    @click="selectDept"
                    icon="el-icon-search"
                  ></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系方式" prop="phone">
                <el-input
                  v-model="formData.phone"
                  placeholder="请填写联系方式"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="使用人数" prop="usePeople">
                <el-input-number
                  v-model="formData.usePeople"
                  controls-position="right"
                  :min="1"
                  :max="100"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="12">
              <el-form-item label="房屋用途" prop="houseUseId">
                <el-select
                  v-model="formData.houseUseId"
                  placeholder="请选择房屋用途"
                  filterable
                  clearable
                  @change="evtHouseUse"
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="(item, index) in houseUseList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <!--
            <el-col :span="12">
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="formData.sex" size="medium">
                  <el-radio
                    v-for="(item, index) in sexOptions"
                    :key="index"
                    :label="item.value"
                    :disabled="item.disabled"
                  >{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="婚否" prop="ifMarried">
                <el-radio-group v-model="formData.ifMarried" size="medium">
                  <el-radio
                    v-for="(item, index) in ifMarriedOptions"
                    :key="index"
                    :label="item.value"
                    :disabled="item.disabled"
                  >{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入职时间" prop="hireDate">
                <el-date-picker
                  v-model="formData.hireDate"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :style="{width: '100%'}"
                  placeholder="请选择日期选择"
                  clearable
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请租用时间" prop="dateTime">
                <el-date-picker
                  v-model="formData.dateTime"
                  type="daterange"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  :style="{width: '100%'}"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  range-separator="至"
                  clearable
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所获荣誉">
                <el-input
                  v-model="formData.otherHonor"
                  type="textarea"
                  placeholder="请输入所获荣誉"
                  :maxlength="200"
                  :autosize="{minRows: 4, maxRows: 4}"
                  :style="{width: '100%'}"
                ></el-input>
              </el-form-item>
            </el-col>-->
            <el-col :span="24">
              <el-form-item label="申请事由">
                <el-input
                  v-model="formData.applyRemark"
                  type="textarea"
                  placeholder="请输入申请事由"
                  :maxlength="500"
                  :autosize="{ minRows: 4, maxRows: 4 }"
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="文件上传">
                <el-upload
                  :limit="limitNum"
                  action="/api/file/upload"
                  accept=".xls, .xlsx, .jpeg, .jpg, .png, .gif, .bmp, .doc, .docx"
                  :data="Imgdata"
                  :headers="headers"
                  :before-upload="beforeUploadFile"
                  :on-change="fileChange"
                  :on-exceed="exceedFile"
                  :on-success="handleSuccess"
                  :on-remove="handRemove"
                  :on-error="handleError"
                  :file-list="fileList"
                >
                  <el-button size="small" type="primary">立即上传</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
        <div class="dialog-footer" style="background-color: #fff; border: none">
          <el-button @click="$router.go(-1)">取 消</el-button>
          <el-button
            class="btn"
            type="primary"
            @click="submitForm"
            :loading="btnLoading"
            >确定</el-button
          >
        </div>
      </div>
    </el-container>
    <!-- 组织机构 -->
    <el-dialog
      :visible.sync="deptFormVisible"
      :close-on-click-modal="false"
      lock-scroll
      append-to-body
      title="服务单位"
      v-loading="deptLoading"
      @close="closeDept"
      ref="addDept"
      width="400px"
    >
      <div class="block" style="height: 350px; overflow-y: auto">
        <el-tree
          :data="treeData"
          ref="tree"
          @check-change="orgCheckChange"
          show-checkbox
          :check-strictly="true"
          node-key="id"
        >
          <span
            class="custom-tree-node"
            style="width: 40%; display: flex; justify-content: space-between"
            slot-scope="{ node, data }"
          >
            <span>{{ data.name }}</span>
          </span>
        </el-tree>
      </div>
      <div class="dialog-footer">
        <el-button @click="deptFormVisible = false">取 消</el-button>
        <el-button @click="addBtn()" type="primary">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { apiProjectDictionary } from "@/api/office/projectDictionaryNew";
import { treeList } from "@/api/user/usercommon";
import { applyRoomApi } from "@/api/office/applyRoomNew";
import Token from "@/itsoftUI/auth/token.js";
import { isNumber } from "@/itsoftUI/utils/validate";
import { validateEmail, validateMobile } from "@/itsoftUI/utils/validate";
export default {
  components: {},
  props: [],
  data() {
    return {
      loading: false,
      deptLoading: false,
      deptFormVisible: false,
      btnLoading: false,
      selectOrg: {
        orgsid: [],
      },
      formData: {
        houseTypeId: undefined,
        flowType: undefined,
        oldRoomInId: undefined,
        userName: undefined,
        userDeptId: undefined,
        titleId: undefined,
        educationName: undefined,
        phone: undefined,
        sex: undefined,
        ifMarried: undefined,
        hireDate: undefined,
        rentStartTime: undefined,
        otherHonor: undefined,
        applyRemark: undefined,
        houseUseId: undefined,
        usePeople: 1,
      },
      limitNum: 6,
      headers: {
        Token: "",
        TokenKey: "",
      },
      Imgdata: { system: "house" },
      fileList: [], // excel文件列表
      fileVOS: [],
      oldRoomList: [],
      houseUseList: [], //房屋用途
      applyType: [
        { id: 1, name: "用房" },
        { id: 2, name: "调整" },
        { id: 3, name: "退房" },
      ],

      houseTypeList: [],
      treeData: [],
      titleIdOptions: [],
      rules: {
        usePeople: [
          {
            required: true,
            message: "请输入使用人数",
            trigger: "change",
          },
        ],
        houseTypeId: [
          {
            required: true,
            message: "请选择申请房屋类",
            trigger: "change",
          },
        ],
        flowType: [
          {
            required: true,
            message: "请选择申请类型",
            trigger: "change",
          },
        ],
        oldRoomInId: [
          {
            required: true,
            message: "请选择退宿房间",
            trigger: "change",
          },
        ],
        userName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "blur",
          },
        ],
        phone: [{ required: true, validator: validateMobile }],
        userDeptName: [
          {
            required: true,
            message: "请选择所在部门",
            trigger: "change",
          },
        ],
        houseUseId: [
          {
            required: true,
            message: "请选择房屋用途",
            trigger: "change",
          },
        ],
        usePeople: [
          {
            required: true,
            message: "请输入使用人数",
            trigger: "blur",
          },
        ],
        sex: [
          {
            required: true,
            message: "性别不能为空",
            trigger: "change",
          },
        ],
        ifMarried: [
          {
            required: true,
            message: "婚否不能为空",
            trigger: "change",
          },
        ],
        hireDate: [
          {
            required: true,
            message: "请选择入职时间",
            trigger: "change",
          },
        ],
        dateTime: [
          {
            required: true,
            message: "请选择申请租用时间",
            trigger: "change",
          },
        ],
        otherHonor: [
          {
            required: true,
            message: "请输入所获荣誉",
            trigger: "blur",
          },
        ],
        applyRemark: [
          {
            required: true,
            message: "请输入申请事由",
            trigger: "blur",
          },
        ],
      },
      field116Action: "https://jsonplaceholder.typicode.com/posts/",
      field116fileList: [],
      Options: [
        {
          label: "选项一",
          value: 1,
        },
        {
          label: "选项二",
          value: 2,
        },
      ],
      flowTypeOptions: [
        {
          label: "选项一",
          value: 1,
        },
        {
          label: "选项二",
          value: 2,
        },
      ],
      userDeptIdOptions: [
        {
          label: "选项一",
          value: 1,
        },
        {
          label: "选项二",
          value: 2,
        },
      ],
      titleIdOptions: [
        {
          label: "选项一",
          value: 1,
        },
        {
          label: "选项二",
          value: 2,
        },
      ],
      sexOptions: [
        {
          label: "男",
          value: 1,
        },
        {
          label: "女",
          value: 2,
        },
      ],
      ifMarriedOptions: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 2,
        },
      ],
      userList: []
    };
  },
  computed: {},
  watch: {},
  methods: {
    funGetUseDept() {
      applyRoomApi.GetUserByDeptId(this.userInfo.userDept).then((res) => {
        this.userList = res.data
      });
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$message.warning(
        `只能选择 ${this.limitNum} 个文件，当前共选择了 ${
          files.length + fileList.length
        } 个`
      );
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {},
    handRemove(file, fileList) {
      if (file.response) {
        for (var i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].path == file.response.data.path) {
            this.fileList.splice(i, 1);
            break;
          }
        }
      } else {
        for (var i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].path == file.path) {
            this.fileList.splice(i, 1);
            break;
          }
        }
      }
      if (file.response) {
        for (var i = 0; i < this.fileVOS.length; i++) {
          if (this.fileVOS[i].path == file.response.data.path) {
            this.fileVOS.splice(i, 1);
            break;
          }
        }
      } else {
        for (var i = 0; i < this.fileVOS.length; i++) {
          if (file.path.indexOf(this.fileVOS[i].path) != -1) {
            this.fileVOS.splice(i, 1);
            break;
          }
        }
      }
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      this.headers.Token = Token.getToken();
      this.headers.TokenKey = Token.getTokenKey();
      this.btnLoading = true;
    },
    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.fileVOS.push(res.data);
      this.$message.success("文件上传成功");
      this.btnLoading = false;
    },
    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message.error("文件上传失败");
      this.btnLoading = false;
    },
    submitForm() {
      this.loading = true;
      let nameList = [];
      let pathList = [];
      this.fileVOS.forEach((el) => {
        nameList.push(el.name);
        pathList.push(el.path);
      });
      this.formData.fileUrl = pathList.toString();
      this.formData.fileName = nameList.toString();
      // this.formData.rentStartTime = this.formData.dateTime[0];
      // this.formData.rentEndTime = this.formData.dateTime[1];
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          applyRoomApi
            .AddApply(JSON.stringify(this.formData))
            .then((res) => {
              if (res.status == "success") {
                this.$message.success("申请成功");
                this.loading = false;
                this.$router.push("home");
              }
            })
            .catch((error) => {
              this.loading = false;
            });
        } else {
          this.loading = false;
        }
      });
    },
    resetForm() {
      this.$refs["elForm"].resetFields();
    },
    BeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2;
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }
      return isRightSize;
    },

    //房屋类型下拉
    funHouseTypeList() {
      let condition = [
        {
          andOr: "and",
          searchField: "typeId",
          operator: "=",
          searchValue: "10718_roomType",
        },
      ];
      apiProjectDictionary
        .dicListFn(2)
        .then((res) => {
          if (res.errorCode === 0) {
            this.houseTypeList = res.data;
          }
        });
    },
    //房屋用途下拉
    funHouseUseList() {
      let condition = [
        {
          andOr: "and",
          searchField: "typeId",
          operator: "=",
          searchValue: "10718_houseUse",
        },
      ];
      apiProjectDictionary
        .dicList("1", JSON.stringify(condition), "num", "asc")
        .then((res) => {
          if (res.errorCode === 0) {
            this.houseUseList = res.data;
          }
        });
    },
    //选择机构
    selectDept() {
      this.deptFormVisible = true;
      treeList().then((res) => {
        this.treeData = res.data;
      });
    },
    //房屋类型名称
    evtHouseType(val) {
      this.houseTypeList.forEach((r) => {
        if (val == r.id) {
          this.formData.houseTypeName = r.name;
        }
      });
    },
    //房屋用途
    evtHouseUse(val) {
      this.houseUseList.forEach((r) => {
        if (val == r.id) {
          this.formData.houseUseName = r.name;
        }
      });
    },
    // 房间列表
    getRoomList() {
      applyRoomApi.ListRoom().then((res) => {
        if (res.status == "success") {
          this.oldRoomList = res.data;
        }
      });
    },
    // 判断用户是否居住
    ifLive() {
      let id_ = "";
      this.oldRoomList.forEach((item) => {
        if (item.id == this.formData.oldRoomInId) {
          id_ = item.id;
        }
      });
      if (id_ == "") {
        return false;
      }
      applyRoomApi.getLiveStatus(id_).catch((error) => {
        this.formData.oldRoomInId = "";
      });
    },
    getUserInfo() {
      applyRoomApi.GetLoginUserInfo().then((res) => {
        this.userInfo = res.data;
        this.formData.account = res.data.account;
        this.$set(this.formData, "userName", res.data.name);
        this.$set(this.formData, "userDeptName", res.data.userDeptName);
        this.formData.userDeptId = res.data.userDept;
        this.formData.userId = res.data.id;
        this.formData.phone = res.data.phone;
        this.funGetUseDept();
      });
    },
    closeDept() {
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]);
      });
    },
    // check-change
    // 节点选中状态发生变化时的回调
    // 共三个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、节点本身是否被选中、节点的子树中是否有被选中的节点
    orgCheckChange(data, checked, indeterminate) {
      // console.log(data, "数据");
      // console.log(checked, "选中状态");
      // console.log(indeterminate, "子树中选中状态");
      // 获取当前选择的id在数组中的索引
      const indexs = this.selectOrg.orgsid.indexOf(data);
      // 如果不存在数组中，并且数组中已经有一个id并且checked为true的时候，代表不能再次选择。
      if (indexs < 0 && this.selectOrg.orgsid.length === 1 && checked) {
        // console.log("only one");
        this.$message({
          message: "只能选择一个单位！",
          type: "error",
          showClose: true,
        });
        // 设置已选择的节点为false 很重要
        this.$refs.tree.setChecked(data, false);
      } else if (this.selectOrg.orgsid.length === 0 && checked) {
        // 发现数组为空 并且是已选择
        // 防止数组有值，首先清空，再push
        this.selectOrg.orgsid = [];
        this.selectOrg.orgsid.push(data);
      } else if (
        indexs >= 0 &&
        this.selectOrg.orgsid.length === 1 &&
        !checked
      ) {
        // 再次直接进行赋值为空操作
        this.selectOrg.orgsid = [];
      }
    },
    funLoadTitle() {
      applyRoomApi.List().then((res) => {
        this.titleIdOptions = res.data.rows;
      });
    },
    addBtn() {
      this.formData.userDeptId = this.selectOrg.orgsid[0].id;
      // this.formData.userDeptName = this.selectOrg.orgsid[0].name;
      this.$set(this.formData, "userDeptName", this.selectOrg.orgsid[0].name);
      this.deptFormVisible = false;
    },
  },
  created() {
    this.funHouseTypeList();
    this.getUserInfo();
    this.funLoadTitle();
    this.getRoomList();
    this.funHouseUseList();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped>
.win-warp {
  ::v-deep .el-form-item--small .el-form-item__content,
  .el-form-item--small .el-form-item__label {
    line-height: 28px;
  }
}
</style>
